import 'dart:math';

import 'package:chathouse/public/Config.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../../model/chartsModel.dart';
import '../../model/template_serivce_model.dart';
import '../../net/Apis.dart';
import '../../public/Obj.dart';
import '../../widgets/base_appbar.dart';
import 'package:characters/characters.dart';

import '../widgets/down_item.dart';
import '../widgets/down_menu_items.dart';

class ChartsPage extends StatefulWidget {
  const ChartsPage({Key? key}) : super(key: key);

  @override
  _ChartsPageState createState() => _ChartsPageState();
}

class ChartData {
  ChartData(this.category, this.sales, this.color);

  final String category;
  final double sales;
  final Color color;
}

class _ChartsPageState extends State<ChartsPage> {
  ChartsModel? model;
  List<ChartData>? chartData;
  List<ChartData>? listData;
  String startTime = "";
  String endTime = "";

  String seleValue = "";
  int idx = -1;


  TemplateServiceModel? clientSearchModel;
  List<CMenuItem>? dataList;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    load();
    loadService();
  }

  loadService() {
    Obj.showLoading();
    Apis.templateServicelist({}).then((response) {
      // Obj.dismissLoading();
      var data = response?.data;
      if (data["code"] != 200) {
        return;
      }
      clientSearchModel = TemplateServiceModel.fromJson(data);
      dataList = getPreviousSixMonths();
      if (seleValue.isNotEmpty) {
        int number = clientSearchModel?.rows?.length ?? 0;
        for (int i = 0; i < number; i++) {
          TemplateServiceItem data = clientSearchModel!.rows![i];
          if (data.serviceName == seleValue) {
            idx = i;
          }
        }
      }
      setState(() {});
    }).catchError((error) {
      // Obj.dismissLoading();
    });
  }

  load() {
    String serviceId = "";
    if (idx != -1) {
      serviceId = clientSearchModel!.rows![idx].serviceId.toString();
    }
    Obj.showLoading();
    Apis.queryChartData({"startDate": startTime, "endDate": endTime, "serviceId":serviceId})
        .then((response) {
      model = ChartsModel.fromJson(response?.data);
      if (model == null) {
        return;
      }
      chartData = [
        ChartData(
            '成功項目數', model!.data!.acceptAlready!.toDouble(), Colors.redAccent),
        ChartData('報價項目數', model!.data!.totalNumberQuotedItems!.toDouble(),
            Colors.blue),
        ChartData('未成交數', model!.data!.acceptStay!.toDouble(), Colors.brown),
        ChartData(
            '已取消數', model!.data!.acceptStay!.toDouble(), Colors.amberAccent),
      ];
      int idx = model?.data?.dataX?.length ?? 0;
      for (int i = 0; i < idx; i++) {
        // ChartData();
      }
      setState(() {});
      Obj.dismissLoading();
    }).onError((error, stackTrace) {
      Obj.dismissLoading();
    });
  }

  List<CMenuItem> getPreviousSixMonths() {
    List<CMenuItem> previousMonths = [];
    int number = clientSearchModel?.rows?.length ?? 0;
    for (int i = 0; i < number; i++) {
      TemplateServiceItem data = clientSearchModel!.rows![i];
      CMenuItem item = CMenuItem(
          label: data.serviceName ?? "", value: data.serviceName ?? "");
      previousMonths.add(item);
    }

    return previousMonths;
  }

  Future<void> _selectDate(BuildContext context, int type) async {
    final DateTime? result = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(DateTime.now().year - 3),
      lastDate: DateTime.now(),
    );
    if (result != null) {
      setState(() {
        if (type == 0) {
          startTime = DateFormat('yyyy-MM-dd').format(result);
        } else {
          endTime = DateFormat('yyyy-MM-dd').format(result);
        }
      });
    }
    if (startTime.isNotEmpty && endTime.isNotEmpty) {
      DateTime start = DateTime.parse(startTime);
      DateTime end = DateTime.parse(endTime);
      if(start.isAfter(end)) {
        String temp = endTime;
        endTime = startTime;
        startTime = temp;
      }
      setState(() {
      });
      load();
    }
  }

  void changeSelectValue(value) {
    seleValue = value;
    int number = clientSearchModel?.rows?.length ?? 0;
    for (int i = 0; i < number; i++) {
      TemplateServiceItem data = clientSearchModel!.rows![i];
      if (data.serviceName == value) {
        idx = i;
      }
    }
    setState(() {});

    load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(title: "接單產量"),
      body: ListView(
        children: [
          Container(
            width: double.infinity,
            alignment: Alignment.center,
            height: 80,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                    onTap: () {
                      _selectDate(context, 0);
                    },
                    child: Text(
                      startTime.isNotEmpty ? startTime : "選擇開始時間",
                      style: TextStyle(fontSize: 20.w),
                    )),
                SizedBox(width: 20.w),
                Text("至", style: TextStyle(fontSize: 20.w)),
                SizedBox(width: 20.w),
                InkWell(
                    onTap: () {
                      _selectDate(context, 1);
                    },
                    child: Text(endTime.isNotEmpty ? endTime : "選擇結束時間",
                        style: TextStyle(fontSize: 20.w))),
              ],
            ),
          ),

          Container(
            alignment: Alignment.center,
            height: 44.w,
            margin: EdgeInsets.symmetric(horizontal: 56.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.w),
              border:
              Border.all(color: MyColors.gary_158157157, width: 1.2.w),
            ),
            child: SelectWidget(
              items: List.generate(dataList?.length ?? 0, (index) {
                return dataList![index];
              }),
              value: seleValue,
              isService: true,
              valueChanged: changeSelectValue,
            ),
          ),
          SizedBox(
            height: 22.w,
          ),
          SfCircularChart(
            title: ChartTitle(
                text: '項目報價數據總結',
                textStyle: TextStyle(fontSize: 20.w, color: Styles.mainColor)),
            legend: Legend(isVisible: true),
            series: <CircularSeries>[
              PieSeries<ChartData, String>(
                explode: true,
                explodeIndex: 0,
                dataSource: chartData,
                xValueMapper: (ChartData data, _) => data.category,
                yValueMapper: (ChartData data, _) => data.sales,
                pointColorMapper: (ChartData data, _) => data.color,
                dataLabelSettings: const DataLabelSettings(
                  isVisible: true,
                ),
              )
            ],
          ),
        ],
      ),
    );
  }
}
